#!/bin/bashi

#### 请在此处输入关键参数，例如程序路径，账号，密码，实例端口###
command_linebin="/mongodb/mongodb-4.0.10/bin"
username="xxx"
password="xxx"
port="27017"
####

####comments0 start 第一次运行此脚本时，自动检查创建备份路径 ####
if [ ! -d "/mongodb/backup/all/mongo-$port" ]; then
    mkdir -p /mongodb/backup/all/mongo-$port
fi

if [ ! -d "/mongodb/backup/all/log-$port" ]; then
    mkdir -p /mongodb/backup/all/log-$port
fi

bkdatapath=/mongodb/backup/all/mongo-$port
bklogpath=/mongodb/backup/all/log-$port

nowtime=$(date "+%Y%m%d")
bkfilename=$nowtime
logfilename=$nowtime

####comments0 end ##

start()
{
    ${command_linebin}/mongodump -h localhost --port $port -u$username -p$password --authenticationDatabase "admin" --oplog --gzip -o $bkdatapath/$bkfilename >> $bklogpath/$logfilename.log 2>&1
}

execute()
{
    echo "===Message --MongoDB端口为"$port"的全量备份开始，开始时间为:"$(date -d today +"%Y%m%d%H%M%S") >> $bklogpath/$logfilename.log

    start

    if [ $? -eq 0 ]; then
        echo "The MongoDB BackUp Successfully!" >> $bklogpath/$logfilename.log
    else 
        echo "The MongoDB BackUp Failure!" >> $bklogpath/$logfilename.log
    fi

    baktime=$(date -d '-7 days' "+%Y%m%d")
    if [ -d "${bkdatapath}/${baktime}/" ]; then
        rm -rf "${bkdatapath}/${baktime}/"
        echo "Message --${bkdatapath}/${baktime}/--删除完毕"  >> $bklogpath/$logfilename.log
    fi

    echo "===Message --MongoDB端口为"$port"的全量备份结束，结束时间为:"$(date -d today +"%Y%m%d%H%M%S") >> $bklogpath/$logfilename.log
}

execute

